<?php
namespace M\Action;
use Common\Action\FirstendAction;
use Common\Model\userModel;
use Common\Model\navModel;
class BaseAction extends FirstendAction{
public function _initialize()
    {
	parent::_initialize();
	$tkapi=trim(C('yh_api_line'));
	$this->tqkuid=C('yh_app_kehuduan');
	$this->assign('trackurl',$this->trackid());
	 $this->assign('openduoduo',C('yh_openduoduo'));
	$this->accessKey = trim(C('yh_gongju'));
	if(false ===$tkapi){
		$this->tqkapi = 'http://api.tuiquanke.com';
		}else{
		$this->tqkapi = $tkapi;
	}
	
	$this->assign('alertwin',$this->_alert_adv());
	
	}

 protected function _alert_adv(){
 	$Ad = S('alertadwap');
    if($Ad){
    	$adlist = $Ad;
    }else{
     $adlist = M('ad')->where('status=4 and add_time = 0')->find();
      S('alertadwap',$adlist,3600);
     }
      return $adlist;
    }


protected function fullurl(){
$mdomain=str_replace('/index.php/m','',C('yh_headerm_html'));
$url=urlencode($mdomain.$_SERVER["REQUEST_URI"]);
return $url;
}


protected function nav(){
$where=array(
'status'=>1,
'type'=>'main'
);
$mod=new navModel();
$navlist=$mod->cache(true, 50 * 60)->field('name,alias,link,target')->where($where)->order('ordid asc')->select();
return $navlist;
}

protected function remoji($str){
       $str = preg_replace_callback( '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;

}

protected function weixinlogin(){
	
	if(C('yh_site_tiaozhuan')==1){
	$useragent = strtolower(addslashes($_SERVER['HTTP_USER_AGENT'])); 
	if(IS_POST && strpos($useragent, 'micromessenger')>0){
	$param=I('post.');
	
	if($param['wx_openkey']==$this->accessKey && $param['wx_status']=='ok'){
	 $res=$this->_wechat_login($param);
	 if(!$res){
	 	
	 if(C('yh_index_ems')==1){
	 	$mod=new userModel();
	 	$track_val=cookie('trackid'); 
	 	
	 	$openuid=F($param['wx_openid']);
	 	
	 	if(!empty($track_val) || $openuid){
        	$track=unserialize($track_val);
        	$uid=$track['t'];
        	if($uid>0){
        		$where=array(
        		'id'=>$uid
        		);
        	}
        	if($openuid>0){
        	$where=array(
        		'id'=>$openuid
        		);	
        	}
        $exist = $mod->field('id,username,nickname,phone,email,fuid,guid,invocode,avatar,password,score,tbname,money,webmaster,webmaster_rate,webmaster_pid,oid')->where($where)->find();
        	}
	 	    $now=NOW_TIME;
	      	$phone = $now;
			$pwd = md5($param['wx_openid']);
			$openid=$param['wx_openid'];
		    $nickname=$param['wx_nickname'];
			
			$nickname=$this->remoji($nickname);
			
        	   $info=array(
            'username'=>$nickname?$nickname:'匿名',
           // 'phone'=>$phone,
            'nickname'=>$nickname?$nickname:'匿名',
            'password'=>$pwd,
            'reg_ip'=>get_client_ip(),
            'avatar'=>$param['wx_headimgurl'],
            'state'=>1,
            'status'=>1,
            'reg_time'=>$now,
            'last_time'=>$now,
            'create_time'=>$now,
            'openid'=>$openid,
            'fuid'=>$exist['id']?$exist['id']:0,
            'guid'=>$exist['fuid']?$exist['fuid']:0
            );
         $res=$mod->add($info);
         $this->reinvi($res);
         $this->visitor->wechatlogin($openid);
	 	
	 }else{
     echo '<form  id="form1" style="display:none" name="form1" method="post" action="'.U('login/fillphone').'">
			  <input name="wx_openid" type="text" value="'.$param['wx_openid'].'"/>
			  <input name="wx_nickname" type="text" value="'.$param['wx_nickname'].'"/>
			  <input name="wx_headimgurl" type="text" value="'.$param['wx_headimgurl'].'"/>
			   <input name="wx_callback" type="text" value="'.$param['wx_callback'].'"/>
			</form>
			<script type="text/javascript">function load_submit(){document.form1.submit()}load_submit();</script>';
	 }	
	
	 }
	 cookie("iswechat", 'error3', 1200);
	 echo('<script>window.location.href="'.$param['wx_callback'].'"</script>');
	}
	 
	}
	
//	cookie("iswechat")!="error3" && 
	if(strpos($useragent, 'micromessenger')>0  && $this->visitor->is_login == false){
	$apiurl='http://app.tuiquanke.cn/wechatlogin?uid='.$this->tqkuid.'&time='.NOW_TIME.'&callback='.$this->fullurl();
     echo('<script>window.location.href="'.$apiurl.'"</script>');
     exit;
	}
	
	}
	
	
}


protected function buyer($num='1'){

$cach_name="buyercache";
$arraytime=array('35','40','50','33','36','42','48','27','6','13','1','12','3','14','5','16','7','18','9','10','15','20','22','30','35','40','50','33','36','42','48','27','6','13');
$datainfo = S($cach_name);
if(false === $datainfo || empty($datainfo)){
$userlist=M('user')->field('nickname,avatar')->where('state=0')->order('rand()')->limit(1000)->select();
S($cach_name,$userlist,86400);
$datainfo=$userlist;
}
$result=array_rand($datainfo,$num);
$timelist=array_rand($arraytime,$num);
foreach($result as $k=>$v){
$data[$k]['nickname']=$this->shortname($datainfo[$v]['nickname']);
$data[$k]['avatar']=$datainfo[$v]['avatar'];
$data[$k]['time']=$timelist[$k];	
}

return $data;
	
}


    protected function trackid(){
        $track=I('t','0','number_int');
        $isagent=cookie('Screateagent');
        $mod=new userModel();
        
     if($this->visitor->is_login){
	$webmaster=$this->visitor->get();
	if($webmaster['webmaster']==1){
	$data=array(
    	't_pid'=>$webmaster['webmaster_pid'],
    	'p_pid'=>$webmaster['pdd_pid'],
    	'recode'=>$res['invocode'],
    	't'=>$webmaster['id'],
    	);
    	 $data=serialize($data);
    	 cookie("trackid", $data, 86400 * 15);
     $trackurl='?t='.$webmaster['id'];
      return $trackurl;
	}
	}
        
        if((!empty($track) && $track!=$isagent && is_numeric($track)) || (false === $isagent && !empty($track) && is_numeric($track))){
        	$res=$mod->field('webmaster_pid,pdd_pid,invocode')->where(array('id'=>$track))->find();
        	if($res){
        	$data=array(
        	't_pid'=>$res['webmaster_pid'],
        	'p_pid'=>$res['pdd_pid'],
        	'recode'=>$res['invocode'],
        	't'=>$track,
        	);
        	$data=serialize($data);
       }
         cookie("trackid", $data, 86400 * 15);
         cookie('Screateagent',$track);
        }
        $trackid=cookie('trackid');
        if(!empty($trackid)){
        	$data=unserialize($trackid);
            $trackurl='?t='.$data['t'];
            return $trackurl;
        }
        

    }
	


protected function shortname($txt){
    $username= mb_substr($txt, 0, 1, 'utf-8').'***'. mb_substr($txt, -1, 1, 'utf-8');
    return $username;
}



protected function getImage($url,$save_dir='',$filename='',$type=0){
		if(trim($url)==''){
			return array('file_name'=>'','save_path'=>'','error'=>1);
		}
		if(trim($save_dir)==''){
			$save_dir='./';
		}
		if(trim($filename)==''){
			$ext=strrchr($url,'.');
			if($ext!='.gif'&&$ext!='.jpg'&&$ext!='.png'&&$ext!='.jpeg'){
				//return array('file_name'=>'','save_path'=>'','error'=>3);
				$ext='.jpg';
			}
			$filename=time().rand(0,10000).$ext;
		}
		if(0!==strrpos($save_dir,'/')){
			$save_dir.="/" . C("yh_attach_path") . 'avatar/';
		}
		if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
			return array('file_name'=>'','save_path'=>'','error'=>5);
		}
		if($type){
			$ch=curl_init();
			$timeout=10;
			curl_setopt($ch,CURLOPT_URL,$url);
			curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
			curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); 
		    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
		    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
			curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
			$img=curl_exec($ch);
			curl_close($ch);
		}else{
			ob_start();
			readfile($url);
			$img=ob_get_contents();
			ob_end_clean();
		}
		$fp2=@fopen($save_dir.$filename,'a');
		fwrite($fp2,$img);
		fclose($fp2);
		unset($img,$url);
		$save_dir = mb_substr($save_dir, 2);
		return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
	}
	

	
	
}
	